using System;
using System.Xml.Linq;

namespace MimeCloud.Foundations.Extensions
{
    public static class XElementExtensions
    {
        public static string GetAttribute(this XElement element, string attributeName)
        {
            var attribute = element.Attribute(attributeName);
            return attribute == null ? "" : (attribute.Value ?? "");
        }
        
        /// <summary>
        /// Gets the value or default.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetValueOrDefault<T>(this XElement parentElement, string elementName)
        {
            try
            {
                var element = parentElement.Element(elementName);
                if (element != null)
                    return (T) Convert.ChangeType(element.Value, typeof (T));

                return default(T);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}